package clock.socoolby.com.clock.fragment.system;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;

import clock.socoolby.com.clock.AboutActivity;
import clock.socoolby.com.clock.ActivateAdmin;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.Constants;
import clock.socoolby.com.clock.MainActivity;
import clock.socoolby.com.clock.R;
import clock.socoolby.com.clock.fragment.houranimator.HourAnimatorFactory;
import clock.socoolby.com.clock.fragment.houranimator.HourVideoFragment;
import clock.socoolby.com.clock.model.DateModel;
import clock.socoolby.com.clock.model.SharePerferenceModel;
import clock.socoolby.com.clock.net.auth.AuthCallback;
import clock.socoolby.com.clock.todo.TodoSyncServiceManager;
import clock.socoolby.com.clock.todo.microsoft.MicrosoftTodoSyncServiceImpl;
import clock.socoolby.com.clock.utils.DialogUtils;
import clock.socoolby.com.clock.utils.FuncUnit;
import clock.socoolby.com.clock.viewmodel.AlterViewModel;
import clock.socoolby.com.clock.viewmodel.GlobalViewModel;
import clock.socoolby.com.clock.viewmodel.ViewModelFactory;
import clock.socoolby.com.clock.widget.animatorview.animator.FishAnimator;
import clock.socoolby.com.clock.widget.wheelview.WheelView;
import clock.socoolby.com.clock.widget.wheelview.adapters.ArrayWheelAdapter;

import static android.content.Context.DEVICE_POLICY_SERVICE;

public class SystemAppConfigFragment  extends Fragment implements View.OnClickListener{
    public static final String TAG= SystemAppConfigFragment.class.getSimpleName();
    private GlobalViewModel globalViewModel;
    private AlterViewModel alterViewModel;

    private WheelView weel_startTime;
    private WheelView weel_stopTime;
    RadioButton rb_halfhour;
    RadioButton rb_hours;
    RadioButton rb_noreport;
    private EditText et_description;
    private EditText et_city;
    String[] listTime = new String[48];

    RadioGroup rg_taking_clock;
    CheckBox cb_tick;
    CheckBox cb_trigger_screen;
    Button btn_uninstall;
    Button btn_about;
    Button btn_save;
    Button btn_exit;

    RadioGroup rg_clock_hour_animator_group;
    RadioButton rg_clock_hour_animator_null;
    RadioButton rg_clock_hour_animator_flash;
    RadioButton rg_clock_hour_video;

    Button btn_clock_hour_video;

    CheckBox cb_boot_start;

    CheckBox cb_handup_overtime_counting;

    CheckBox cb_fullscreen_spirit;

    EditText et_handup_deily;

    CheckBox cb_todo_sync_able;

    CheckBox cb_trigger_system_wallpaper;

    private SharePerferenceModel model;

    public SystemAppConfigFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.globalViewModel = ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(GlobalViewModel.class);
        alterViewModel=ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(AlterViewModel.class);
        globalViewModel.setAppConfig(true);
        model=ClockApplication.getInstance().getModel();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View themeRootView = inflater.inflate(R.layout.fragment_setting, container, false);

        rg_taking_clock =  themeRootView.findViewById(R.id.rg_talking_clock);
        rb_halfhour =  themeRootView.findViewById(R.id.rb_halfhour);
        rb_hours =  themeRootView.findViewById(R.id.rb_hours);
        rb_noreport = themeRootView.findViewById(R.id.rb_noreport);
        weel_startTime = themeRootView.findViewById(R.id.weel_start_time);
        weel_stopTime =  themeRootView.findViewById(R.id.weel_stop_time);

        et_city =themeRootView.findViewById(R.id.et_city);
        et_description =  themeRootView.findViewById(R.id.et_description);

        rg_clock_hour_animator_group=themeRootView.findViewById(R.id.rg_clock_hour_animator_group);
        rg_clock_hour_animator_null=themeRootView.findViewById(R.id.rg_clock_hour_animator_null);
        rg_clock_hour_animator_flash=themeRootView.findViewById(R.id.rg_clock_hour_animator_flash);
        rg_clock_hour_video=themeRootView.findViewById(R.id.rg_clock_hour_video);
        btn_clock_hour_video=themeRootView.findViewById(R.id.btn_clock_hour_video);

        cb_boot_start=themeRootView.findViewById(R.id.cb_boot_start);

        cb_tick = themeRootView.findViewById(R.id.cb_tick);
        cb_trigger_screen = themeRootView.findViewById(R.id.cb_trigger_screen);
        btn_uninstall = themeRootView.findViewById(R.id.btn_uninstall);
        btn_about =  themeRootView.findViewById(R.id.btn_about);
        btn_save= themeRootView.findViewById(R.id.btn_save);
        btn_exit=themeRootView.findViewById(R.id.btn_exit);

        et_handup_deily=themeRootView.findViewById(R.id.et_handup_deily);
        cb_handup_overtime_counting=themeRootView.findViewById(R.id.cb_handup_overtime_counting);
        cb_fullscreen_spirit=themeRootView.findViewById(R.id.cb_fullscreen_spirit);
        cb_todo_sync_able=themeRootView.findViewById(R.id.cb_todo_alter_able);

        cb_trigger_system_wallpaper=themeRootView.findViewById(R.id.cb_trigger_system_wallpaper);

        loadDataFromModel();

        btn_about.setOnClickListener(this);
        btn_uninstall.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        btn_exit.setOnClickListener(this);
        cb_trigger_screen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        AccessibilityManager manager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
                        if (!manager.isEnabled()) {
                            DialogUtils.show(getContext(),"提醒","当前功能须要开启补助功能，是不前往。", ok->{
                                if(ok){
                                    getActivity().startActivityForResult(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), Constants.ACCESSIBILITY_SERVICE_REQUEST_CODE);
                                }
                            });
                            cb_trigger_screen.setChecked(false);
                            return;
                        }
                    }
                }
                model.setTriggerScreen(isChecked);
            }
        });

        cb_tick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                model.setTickSound(b);
            }
        });

        cb_boot_start.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                model.setBootStart(isChecked);
            }
        });

        rg_clock_hour_animator_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btn_clock_hour_video.setVisibility(View.GONE);
                switch (checkedId){
                    case R.id.rg_clock_hour_animator_null:
                        model.setTimeHourAlterTypeName(HourAnimatorFactory.DEFAULT);
                        break;
                    case R.id.rg_clock_hour_animator_flash:
                        model.setTimeHourAlterTypeName(FishAnimator.NAME);
                        break;
                    case R.id.rg_clock_hour_video:
                        model.setTimeHourAlterTypeName(HourVideoFragment.NAME);
                        btn_clock_hour_video.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });

        btn_clock_hour_video.setOnClickListener(this);

        ArrayWheelAdapter<String> timeAdpater = new ArrayWheelAdapter<String>(getContext(), listTime);
        weel_startTime.setViewAdapter(timeAdpater);
        ArrayWheelAdapter<String> durationAdapter = new ArrayWheelAdapter<String>(getContext(), listTime);
        weel_stopTime.setViewAdapter(durationAdapter);

        rg_taking_clock.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int index) {
                int checkID = radioGroup.getCheckedRadioButtonId();
                switch (checkID) {
                    case R.id.rb_halfhour:
                        model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
                        break;
                    case R.id.rb_hours:
                        model.setTypeHourPower(Constants.TALKING_HOURS);
                        break;
                    case R.id.rb_noreport:
                        model.setTypeHourPower(Constants.TALKING_NO_REPORT);
                        break;

                }

            }
        });

        cb_handup_overtime_counting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                model.setHandUpOverTimeCountingAble(isChecked);
            }
        });

        cb_fullscreen_spirit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                model.setFullscreenSpiritAble(isChecked);
            }
        });

        cb_trigger_system_wallpaper.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                model.setUseSystemWallpaper(isChecked);
            }
        });

        cb_todo_sync_able.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    TodoSyncServiceManager todoSyncServiceManager=globalViewModel.getTodoSyncServiceManager();
                    todoSyncServiceManager.start();
                    todoSyncServiceManager.singIn(MicrosoftTodoSyncServiceImpl.NAME, getActivity(), new AuthCallback() {
                        @Override
                        public void onSuccess() {
                            globalViewModel.setTodoSyncAble(true);
                        }

                        @Override
                        public void onError(Exception exception) {
                            cb_todo_sync_able.setChecked(false);
                        }

                        @Override
                        public void onCancel() {
                            cb_todo_sync_able.setChecked(false);
                        }
                    });
                }else
                  globalViewModel.setTodoSyncAble(false);
            }
        });

        return themeRootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        globalViewModel.setAppConfig(false);
    }

    private void loadDataFromModel() {

        for (int i = 0; i < 48; i++) {
            int hours = i / 2;
            int minutes = i % 2 * 30;
            String timeString = String.format("%02d:%02d", hours, (minutes + 1));
            listTime[i] = timeString;
        }

        int startTimeIndex = indexOfTimeString(String.format("%02d:%02d", model.getStartHourPowerTime().getHour(), model.getStartHourPowerTime().getMinute()));
        int stopTimeIndex = indexOfTimeString(String.format("%02d:%02d", model.getStopHourPowerTime().getHour(), model.getStopHourPowerTime().getMinute()));
        weel_startTime.setCurrentItem(startTimeIndex);
        weel_stopTime.setCurrentItem(stopTimeIndex);

        cb_tick.setChecked(model.isTickSound());

        cb_trigger_screen.setChecked(model.isTriggerScreen());

        switch (model.getTypeHourPower()) {
            case Constants.TALKING_HALF_AN_HOUR:
                rb_halfhour.setChecked(true);
                break;
            case Constants.TALKING_HOURS:
                rb_hours.setChecked(true);
                break;
            case Constants.TALKING_NO_REPORT:
                rb_noreport.setChecked(true);
                break;
        }
        et_city.setText(model.getCity());
        et_description.setText(model.getDescription());

        cb_boot_start.setChecked(model.isBootStart());

        btn_clock_hour_video.setVisibility(View.GONE);

        switch (model.getTimeHourAlterTypeName()){
            case FishAnimator.NAME:
                rg_clock_hour_animator_flash.setChecked(true);
                break;
            case HourVideoFragment.NAME:
                btn_clock_hour_video.setVisibility(View.VISIBLE);
                rg_clock_hour_video.setChecked(true);
                btn_clock_hour_video.setText(model.getTimeHourVideoPath());
                break;
            default:
                rg_clock_hour_animator_null.setChecked(true);
        }

        cb_handup_overtime_counting.setChecked(model.isHandUpOverTimeCountingAble());
        et_handup_deily.setText(model.getHandUpDialy().toString());

        cb_fullscreen_spirit.setChecked(model.isFullscreenSpiritAble());

        cb_todo_sync_able.setChecked(model.isTodoSyncAble());

        cb_trigger_system_wallpaper.setChecked(model.isUseSystemWallpaper());
    }

    private void saveToModel() {
        reportTimeConfirm();
        model.setCity(et_city.getText().toString());
        model.setDescription(et_description.getText().toString());
        String dialyStr=et_handup_deily.getText().toString();
        Integer dialy=0;
        if(dialyStr!=null&&!dialyStr.isEmpty())
              dialy=Integer.valueOf(dialyStr);
        //model.setHandUpDialy(dialy);
        alterViewModel.setHandUPDialy(dialy);
        globalViewModel.loadFromModel();
    }

    private int indexOfTimeString(String timeString) {
        for (int i = listTime.length - 1; i >= 0; i--) {
            if (listTime[i].equals(timeString))
                return i;
        }
        return 0;
    }

    private void reportTimeConfirm() {
        String timeStart = listTime[weel_startTime.getCurrentItem()];
        String timeStop = listTime[weel_stopTime.getCurrentItem()];

        DateModel startTimeModel = new DateModel();
        startTimeModel.setTimeString(timeStart);
        DateModel stopTimeModel = new DateModel();
        stopTimeModel.setTimeString(timeStop);
        model.setStartHourPowerTime(startTimeModel);
        model.setStopHourPowerTime(stopTimeModel);
    }

    private void uninstallActivity() {
        DevicePolicyManager policyManager;
        ComponentName componentName;
        policyManager = (DevicePolicyManager) getActivity().getSystemService(DEVICE_POLICY_SERVICE);

        componentName = new ComponentName(getActivity(), ActivateAdmin.class);
        policyManager.removeActiveAdmin(componentName);
        startActivity(new Intent("android.intent.action.DELETE", Uri.parse("package:" + FuncUnit.getBoxPackageName())));
        getActivity().finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_uninstall:
                uninstallActivity();
                break;
            case R.id.btn_about:
                Intent intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_save:
                saveToModel();
                getFragmentManager().popBackStack();
                break;
            case R.id.btn_clock_hour_video:
                configHourVideo();
                btn_clock_hour_video.setText(model.getTimeHourVideoPath());
                break;
            case R.id.btn_exit:
                getActivity().finish();
                break;
        }
    }

    public void configHourVideo() {
        PictureSelector.create(getActivity())
                .openGallery(PictureMimeType.ofVideo())
                .isCamera(false)
                .imageSpanCount(4)
                .forResult(PictureConfig.TYPE_VIDEO);
    }
}
